package com.qjc.demo.thread.countDownLatch;

import java.util.concurrent.*;

/**
 * @Description:
 * @Author: qjc
 * @Date: 2020/7/17
 */
public class CountDownLatchTest2 {

    private final static int THREAD_POOL_SIZE = 2;
    private final static long KEEP_ALIVE_TIME = 0L;

    public static void main(String[] args) throws InterruptedException {
        final CountDownLatch countDownLatch = new CountDownLatch(2);
//        ExecutorService executorService = Executors.newFixedThreadPool(2);
        ExecutorService executorService = new ThreadPoolExecutor(THREAD_POOL_SIZE, THREAD_POOL_SIZE, KEEP_ALIVE_TIME,
                TimeUnit.MILLISECONDS, new LinkedBlockingDeque<>(10), new ThreadPoolExecutor.AbortPolicy());
        executorService.submit(() -> {
            try {
                Thread.sleep(1000);
                System.out.println("子线程A运行1s");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                countDownLatch.countDown();
            }
            try {
                Thread.sleep(2000);
                System.out.println("子线程A又运行了2s");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        executorService.submit(() -> {
            try {
                Thread.sleep(1000);
                System.out.println("子线程B运行1s");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                countDownLatch.countDown();
            }
            try {
                Thread.sleep(2000);
                System.out.println("子线程B又运行了2s");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        System.out.println("等待子线程运行1s完毕");
        //等待子线程运行完毕
        countDownLatch.await();
        long count = countDownLatch.getCount();


        System.out.println("countDownLatch：" + count + "，所有子线程工作了1s，主线程就可以干其他事儿，不用管子线程后面的运行");
        executorService.shutdown();
    }

}
